import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index'
import { useUserStore } from '@/stores/user'

const http = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000
})

// 请求拦截器
http.interceptors.request.use(
  function (config) {
    const userstore = useUserStore()
    const token = userstore.userInfo.token
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    if (response.data.code === 200) {
      return response
    }
    ElMessage.error(response.data.msg)
    return Promise.reject(response)
  },
  function (error) {
    const message = error.response?.data?.msg || '网络错误'

    if (error.response?.status === 401) {
      ElMessage.error('登录已过期')
      router.push('/login')
    } else {
      ElMessage.error(message)
    }
    return Promise.reject(error)
  }
)

export default http
